import configparser
import hashlib
import os
import re
import sys
import time

import requests

import run_exinfo
import xcode
from get_log import GetLog


class Srun:
    def __init__(self):
        self.conf = None
        self.username = None
        self.password = None

        self.i = None
        self.token = None
        self.hmd5 = None
        self.chksum = None
        self.ac_id = None
        self.ip = None
        self.n = '200'
        self.type = '1'
        self.enc = 'srun_bx1'

        self.init_url = None
        self.get_challenge_api = None
        self.srun_portal_api = None
        self.header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36'}
        self.init_exinfo()

    def init_exinfo(self):
        run_exinfo.run()
        time.sleep(0.5)
        logger.info('ex_info has been launched.')

    def clean_exinfo(self):
        run_exinfo.exit0()
        time.sleep(0.2)
        logger.info('ex_info has been exited.')

    def setuser(self, username, password):
        self.username = username
        self.password = password

    def get_config(self):
        self.conf = configparser.ConfigParser()
        if not os.path.exists('config.conf'):
            self.conf["xjuFN"] = {"saddress": "http://202.201.252.10/"}
            with open("config.conf", "w") as fp:
                self.conf.write(fp)
            print("已在当前目录生成配置文件，请修改后重试！")
            sys.exit()

        self.conf.read("config.conf")
        self.init_url = self.conf["xjuFN"]["saddress"]
        self.get_challenge_api = self.init_url + "cgi-bin/get_challenge"
        self.srun_portal_api = self.init_url + "cgi-bin/srun_portal"

        self.ac_id = self.between(requests.get(url=self.init_url + 'index_1.html', allow_redirects=False).text,
                                  'ac_id=', '&amp')

    def get_checksum(self):
        chkstr = self.token + self.username
        chkstr += self.token + self.hmd5
        chkstr += self.token + self.ac_id
        chkstr += self.token + self.ip
        chkstr += self.token + self.n
        chkstr += self.token + self.type
        chkstr += self.token + self.i
        return chkstr

    def get_info(self):
        info_temp = {
            "username": self.username,
            "password": self.password,
            "ip": self.ip,
            "acid": self.ac_id,
            "enc_ver": self.enc
        }
        i = re.sub("'", '"', str(info_temp))
        i = re.sub(" ", '', i)
        return i

    def between(self, string, leftstr, rightstr):
        try:
            rule = r'{}(.*?){}'.format(leftstr, rightstr)
            slot = re.findall(rule, string)[0]
            return slot
        except:
            return ''

    def init_getip(self):
        init_res = requests.get(self.init_url, headers=self.header)
        self.ip = self.between(init_res.text, 'ip     : "', '",')

    def get_token(self):
        get_challenge_params = {
            "callback": "jQuery112404953340710317169_" + str(int(time.time() * 1000)),
            "username": self.username,
            "ip": self.ip,
            "_": int(time.time() * 1000),
        }
        get_challenge_res = requests.get(self.get_challenge_api, params=get_challenge_params, headers=self.header)
        self.token = re.search('"challenge":"(.*?)"', get_challenge_res.text).group(1)

    def get_md5(self, text):
        data = text + self.token
        md5_str = hashlib.md5(data.encode()).hexdigest()
        return md5_str

    def do_complex_work(self):
        self.i = self.get_info()
        url = 'http://localhost:3003/getData'
        params = {
            'info': self.i,
            'token': self.token,
        }

        sign = requests.get(url, params=params)
        sign = sign.json().get('data')
        self.i = sign

        self.hmd5 = self.get_md5(self.password)
        self.chksum = xcode.get_sha1(self.get_checksum())

    def get_srun_portal_params(self, logout=False):
        srun_portal_params = {
            'callback': 'jQuery11240645308969735664_' + str(int(time.time() * 1000)),
            'action': 'login',
            'username': self.username,
            'password': '{MD5}' + self.hmd5,
            'ac_id': self.ac_id,
            'ip': self.ip,
            'chksum': self.chksum,
            'info': self.i,
            'n': self.n,
            'type': self.type,
            'os': 'Windows 95',
            'name': 'Windows',
            'double_stack': '1',
            '_': int(time.time() * 1000)
        }
        if logout:
            srun_portal_params['action'] = 'logout'
        return srun_portal_params

    def login(self):
        self.init_getip()
        self.get_token()
        self.do_complex_work()
        srun_portal_params = self.get_srun_portal_params()
        srun_portal_res = requests.get(self.srun_portal_api, params=srun_portal_params, headers=self.header)
        logger.info(srun_portal_res.text)
        self.clean_exinfo()

    def logout(self):
        self.init_getip()
        self.get_token()
        self.do_complex_work()
        srun_portal_params = self.get_srun_portal_params(logout=True)
        srun_portal_res = requests.get(self.srun_portal_api, params=srun_portal_params, headers=self.header)
        logger.info(srun_portal_res.text)
        self.clean_exinfo()


logger = GetLog().get_log('logs')
